<template>
  <div class="app-container">
    <el-col v-if="showTable">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="handleExportDetails"
          v-hasPermi="['optimize:package:export']"
        >导出筛选明细</el-button>
      </el-col>
      <el-col :span="1.5" class="right-align-col">
        <el-button
          type="success"
          plain
          icon="Download"
          @click="handleExportPdfs"
          v-hasPermi="['optimize:package:export']"
        >导出筛选排版</el-button>
      </el-col>
    </el-row>

    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
      <el-form-item label="优化包名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入优化包名称"
          @keyup.enter="handleQuery"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item label="切割下发时间">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="请选择起始时间"
          end-placeholder="请选择结束时间"
          :disabled-date="time => time.getTime() > Date.now()"
          style="width: 400px"
          @change="handleDateRangeChange"
        />
      </el-form-item>
      <el-form-item label="切裁率" prop="beginRateEdge">
        <el-input
          v-model="queryParams.beginRateEdge"
          placeholder="请输入切裁率下限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="endRateEdge">
        <el-input
          v-model="queryParams.endRateEdge"
          placeholder="请输入切裁率上限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
        <el-form-item label="净切裁率" prop="beginRateNoEdge">
            <el-input
            v-model="queryParams.beginRateNoEdge"
            placeholder="请输入净切裁率下限"
            @keyup.enter="handleQuery"
            style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="endRateNoEdge">
        <el-input
            v-model="queryParams.endRateNoEdge"
          placeholder="请输入净切裁率上限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="原片数" prop="beginOriginalNumber">
        <el-input
          v-model="queryParams.beginOriginalNumber"
          placeholder="请输入原片数下限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="optimizeResult.endOriginalNumber">
        <el-input
          v-model="queryParams.endOriginalNumber"
          placeholder="请输入原片数上限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="余料宽度" prop="optimizeResult.beginResidueLength">
        <el-input
          v-model="queryParams.beginResidueLength"
          placeholder="请输入余料宽度下限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="optimizeResult.endResidueLength">
        <el-input
          v-model="queryParams.endResidueLength"
          placeholder="请输入余料宽度上限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>    
    </el-form>
    <el-table v-loading="loading" :data="packageList" 
    @sort-change="handleSortChange">
      <el-table-column label="优化包名称" align="center" sortable="custom" prop="name" />
      <el-table-column label="切割下发时间" align="center" sortable="custom" prop="confirmTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.confirmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="切割完成时间" align="center" sortable="custom" prop="completeTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.completeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="切裁率" align="center" sortable="custom" prop="optimizeResult.rateEdge">
        <template #default="scope">
          <span>{{ (scope.row.optimizeResult.rateEdge).toFixed(2) }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="净切裁率" align="center" sortable="custom" prop="optimizeResult.rateNoEdge">
        <template #default="scope">
          <span>{{ (scope.row.optimizeResult.rateNoEdge).toFixed(2) }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="成品总面积" align="center" sortable="custom" prop="optimizeResult.glassArea">
        <template #default="scope">
          <span>{{ (scope.row.optimizeResult.glassArea).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原片总面积" align="center" sortable="custom" prop="optimizeResult.totalArea">
        <template #default="scope">
          <span>{{ (scope.row.optimizeResult.totalArea).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原片数" align="center" sortable="custom" prop="optimizeResult.originalNumber" />
      <el-table-column label="余料宽度" align="center" sortable="custom" prop="optimizeResult.residueLength" /> 
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width" width="300">
        <template #default="scope">
          <el-button link type="primary" @click="handleView(scope.row)"
            v-hasPermi="['optimize:package:edit']">查看排版</el-button>
          <el-button link type="primary" @click="handleExport(scope.row, scope.row.name)"
            v-hasPermi="['optimize:package:export']">导出明细</el-button>
          <el-button link type="primary" @click="handleExportOpt(scope.row, scope.row.name)"
            v-hasPermi="['optimize:package:export']">导出切割代码</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      />
    </el-col>
  <!-- 排版页面 -->
  <el-dialog :title="title" v-model="openPdf" width="60%" append-to-body>
      <div class="controls" v-if="totalPages > 0">
        <el-button 
          type="primary"
          @click="currentPage--" 
          :disabled="currentPage <= 1"
          class="page-btn prev-btn"
        >
          上一页
        </el-button>
        <el-input 
          v-model="currentPage" 
          type="number" 
          :min="1" 
          :max="totalPages"
          style="width: 60px; text-align: center; margin: 0 10px;"
          @change="handlePageChange(currentPage)"
        />
        <span class="page-info">/ {{ totalPages }}</span>
        <el-button
          type="primary" 
          @click="currentPage++"
          :disabled="currentPage >= totalPages"
          class="page-btn next-btn"
        >
          下一页
        </el-button>
      </div>
      <PDF v-if="openPdf" :src="pdfSrc" 
      :page="currentPage"
      :pdfWidth="`${scale}%`"
      style="width: 100%; height: 80vh;" 
      @onComplete="pdfLoaded" 
      @onPageChange="handlePageChange" 
      
      ref="pdfViewer"
      >
      <template #pageTooltip="{ pageNumber, totalPages }">
        <div ref="tooltipRef">{{ updateTotalPages(totalPages) }}</div>
    </template>
    </PDF>
    </el-dialog> 
  <!-- <el-dialog :title="title" v-model="openPdf" width="90%" append-to-body>
      <PDF v-if="openPdf" :src="pdfSrc" style="width: 100%; height: 70vh;" :oncomplete="pdfLoaded" />
    </el-dialog> -->
  </div>
</template>
<script setup name="RecordPackage">

import {  getConfirmedPackageList, exportOpt,exportPdf,exportPdfShow } from "@/api/optimize/package";


import PDF from 'pdf-vue3'
import useOrderStore from '@/store/modules/order'

const orderStore = useOrderStore();
const { proxy } = getCurrentInstance();

const packageList = ref([]);
const loading = ref(false);
const total = ref(0);
const showTable = ref(true);
const packageDetailList = ref([]);
const packageOgList = ref([]);
const plateList = ref([]);
const currentId = ref(null);
const currentName = ref(null);
const rectangles = ref([]);
const openPdf = ref(false);
const pdfSrc = ref('');
const title = ref("");
const stageConfig = ref({
  width: 600,
  height: 600
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createrId: null,
    name: null,
    beginConfirmTime: null,
    endConfirmTime: null,
    beginRateEdge: null,
    endRateEdge: null,
    beginRateNoEdge: null,
    endRateNoEdge: null,
    beginOriginalNumber: null,
    endOriginalNumber: null,
    beginResidueLength : null,
    endResidueLength: null,
  },
  rules: {
  }
});
const { queryParams, form, rules } = toRefs(data);

const dateRange = ref(null);

function handleDateRangeChange(val) {
  if (val) {
    queryParams.value.beginConfirmTime = val[0];
    queryParams.value.endConfirmTime = val[1];
  } else {
    queryParams.value.beginConfirmTime = null;
    queryParams.value.endConfirmTime = null;
  }
  handleQuery();
}

function handleExportDetails() {
  const ids = packageList.value.map(item => item.id).join(',');
  proxy.$download.zip("/optimize/package/export/details/" + ids, "optimize_details.zip");
}

function handleExportPdfs() {
  const ids = packageList.value.map(item => item.id).join(',');
  proxy.$download.zip("/optimize/package/export/pdfs/" + ids, "optimize_pdfs.zip");
}

function handleSortChange(column) {
  queryParams.value.orderByColumn = column.prop;
  if(column.order == 'ascending') {
    queryParams.value.isAsc = 'ASC';
  } else if(column.order == 'descending') {
    queryParams.value.isAsc = 'DESC';
  } else {
    queryParams.value.isAsc = null;
    queryParams.value.orderByColumn = null;
  }
  getList();
}

//pdf相关
const totalPages = ref(0);
const currentPage = ref(1);
const scale = ref(100);
const tooltipRef = ref(null);
const pdfViewer = ref(null);



function updateTotalPages(num){
  totalPages.value = num;
}

function pdfLoaded(){
  //totalPages.value = pdfViewer.value.getPageCount();
  console.log("pdfLoaded",pdfViewer.value)
}

function handlePageChange(page){
  currentPage.value = page;
}




function handleBack() {
  packageDetailList.value = [];
  packageOgList.value = [];
  plateList.value = [];
  showTable.value = true;
  rectangles.value = [];
  currentId.value = null;
  currentName.value = null;
}

function handleOgChange(row){
  
  const width = row.width;
  const height = row.height;
  const ration = width / 600;
  const tWidth = width / ration;
  const tHeight = height / ration;
  stageConfig.value.width = tWidth;
  stageConfig.value.height = tHeight;

  rectangles.value = [];
  for(let i = 0; i < packageDetailList.value.length; i++){
    if(packageDetailList.value[i].sn == row.sn){
      const detail = packageDetailList.value[i];
 
      const dWidth = detail.width / ration;
      const dHeight = detail.height / ration;
      const x = detail.xDistance / ration;
      const y = tHeight - detail.yDistance / ration - dHeight;
      const frameNo = detail.frameNo + detail.firstEnd + "#" + detail.seq;
      const showWidth = detail.width;
      const showHeight = detail.height;
      const showBoxNo = detail.boxNo.substring(0, detail.boxNo.indexOf('.') + 2);
      rectangles.value.push({ x: x, y: y, width: dWidth, height: dHeight,frameNo: frameNo,showWidth: showWidth,showHeight: showHeight,showBoxNo: showBoxNo });
    }
  }
}

function handleQuery() {
  if (queryParams.value.confirmTime && queryParams.value.confirmTime.length > 1) {
    queryParams.value.beginConfirmTime = queryParams.value.confirmTime[0];
    queryParams.value.endConfirmTime = queryParams.value.confirmTime[1];
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef"); 
  dateRange.value = null;
  queryParams.value.beginConfirmTime = null;
  queryParams.value.endConfirmTime = null;
  handleQuery();
}

function getList() {
  
  getConfirmedPackageList(queryParams.value).then(response => {
    packageList.value = response.rows;
    total.value = response.total;
  });
}

// 查看排版
function handleView(row) {
  openPdf.value = false; // 先关闭对话框
  title.value = "排版预览 - " + row.name;
  // 使用nextTick确保DOM更新后再打开对话框
  nextTick(() => {
     let type = row.cutReverse == 0 ? 'forward' : 'reverse';
     let version = orderStore.pdfLayoutRule || '1'
    exportPdfShow(row.id,type,'left',version).then(response => {
      pdfSrc.value = response.data
      openPdf.value = true
  });

  });
  // openPdf.value = false; // 先关闭对话框
  // title.value = "排版预览 - " + row.name;
  
  // // 使用nextTick确保DOM更新后再打开对话框
  // nextTick(() => {
  //   pdfSrc.value = 'http://localhost:8080/algorithm/' + row.name + '_forward_left.pdf';
  //   openPdf.value = true; // 再打开对话框
  // });
}

function handleExport(row,name) {
  proxy.$download.zip("/optimize/package/export/detail/" + row.id, name + ".zip");
}

function handleExportOpt(row, name) {
  const filename = name + "_forward.opt";
  exportOpt(row.id).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, filename);
  });
}

function handleExportPdf() {
  if(!currentId.value) {
    proxy.msgError("请先选择优化包");
    return;
  }
  if(!currentName.value) {
    currentName.value = packageList.value.find(item => item.id == currentId.value).name;
  }
  const filename = currentName.value + "_forward.pdf";
  exportPdf(currentId.value).then(response => {
    const blob = new Blob([response])
    proxy.$download.saveAs(blob, filename);
  });
}

onActivated(() => {
  getList();
});

</script>

<style scoped>
.page-btn {
  margin-right: 10px;
}

.page-info {
  margin: 0 10px;
}

.controls {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  background-color: #f0f8ff;
}

.prev-btn {
  margin-right: 10px;
}

</style>